package cn.edu.swu.multimedia

import android.annotation.SuppressLint
import android.app.NotificationManager
import android.content.Context
import android.media.MediaPlayer
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.VideoView

class PlayMusicActivity : AppCompatActivity() {
    private val mediaPlayer = MediaPlayer()
    @SuppressLint("ServiceCast")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as
                NotificationManager
        manager.cancel(1)
        initMediaPlayer()
        val playMusic: Button = findViewById(R.id.playMusic)
        playMusic.setOnClickListener {
            if (!mediaPlayer.isPlaying) {
                mediaPlayer.start() // 开始播放
            }
        }
        val pauseMusic: Button = findViewById(R.id.pauseMusic)
        pauseMusic.setOnClickListener {
            if (mediaPlayer.isPlaying) {
                mediaPlayer.pause() // 暂停播放
            }
        }
        val stopMusic: Button = findViewById(R.id.stopMusic)
        stopMusic.setOnClickListener {
            if (mediaPlayer.isPlaying) {
                mediaPlayer.reset() // 停止播放
                initMediaPlayer()
            }
        }
        // 播放视频
        val uri = Uri.parse("android.resource://$packageName/${R.raw.video}")
        val videoView: VideoView = findViewById(R.id.videoView)
        videoView.setVideoURI(uri)
        val playVideo: Button = findViewById(R.id.playVideo)
        playVideo.setOnClickListener {
            if (!videoView.isPlaying) {
                videoView.start() // 开始播放
            }
        }
        val pauseVideo: Button = findViewById(R.id.pauseVideo)
        pauseVideo.setOnClickListener {
            if (videoView.isPlaying) {
                videoView.pause() // 暂停播放
            }
        }
        val replayVideo: Button = findViewById(R.id.replayVideo)
        replayVideo.setOnClickListener {
            if (videoView.isPlaying) {
                videoView.resume() // 重新播放
            }
        }
    }
    private fun initMediaPlayer() {
        val assetManager = assets
        val fd = assetManager.openFd("music.mp3")
        mediaPlayer.setDataSource(fd.fileDescriptor, fd.startOffset, fd.length)
        mediaPlayer.prepare()
    }
    override fun onDestroy() {
        super.onDestroy()
        mediaPlayer.stop()
        mediaPlayer.release()
        val videoView: VideoView = findViewById(R.id.videoView)
        videoView.suspend()

    }

}